﻿using System.Collections.Generic;
using System.Data.Common;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Linq;
using System.Transactions;

namespace ASPItalia.ModelVirtualCasting.EntityFramework
{
	public class BaseRepository<T> where T : class
	{
		public BaseRepository(IContextContainer container)
		{
			Context = container.Current;
			CurrentObjectQuery = CreateObjectQuery();
			Commands = new List<EntityCommand>();
		}

		protected ObjectQuery<T> CurrentObjectQuery { get; set; }
		protected ModelVirtualCastingEntities Context { get; set; }
		protected List<EntityCommand> Commands { get; set; }
		protected bool CreateNewContextAfterSaveChanges { get; set; }

		protected void SaveChanges()
		{
			if (Commands.Any())
			{
				using (TransactionScope scope = new TransactionScope())
				{
					Context.Connection.Open();
					Commands.ForEach(c => ExecuteQuery(c, Context.Connection));
					Context.SaveChanges();
					scope.Complete();
				}
			}
			else
			{
				Context.SaveChanges();
			}
			if (CreateNewContextAfterSaveChanges)
				Context = new ModelVirtualCastingEntities();
		}

		private void ExecuteQuery(DbCommand c, DbConnection connection)
		{
			c.Connection = connection;
			c.ExecuteNonQuery();
		}

		protected ObjectQuery<T> CreateObjectQuery()
		{
			return Context.CreateObjectSet<T>();
		}

		protected void SetLazyLoading(bool enabled)
		{
			Context.ContextOptions.LazyLoadingEnabled = enabled;
		}
	}
}
